package com.sunsharing.container;

import com.sunsharing.common.Constant;
import com.sunsharing.common.Context;
import com.sunsharing.common.anno.AnoClassCretator;
import com.sunsharing.common.anno.AnoClassCretator;
import com.sunsharing.common.config.ChannelModel;
import com.sunsharing.common.config.Config;
import com.sunsharing.dispatch.Dispatch;
import com.sunsharing.transport.Channel;
import com.sunsharing.transport.Client;
import com.sunsharing.transport.IoHandle;
import com.sunsharing.transport.Server;
import com.sunsharing.transport.mina.MinaServer;
import com.sunsharing.transport.netty.NettyServer;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * User: criss
 * Date: 13-4-8
 * Time: 下午8:49
 * To change this template use File | Settings | File Templates.
 */
public class ServerCreater {

    static final Logger logger = Logger.getLogger(ServerCreater.class);

    private static List<Server> servers = new ArrayList<Server>();

    public static void initServer()
    {
        Config config = Config.getInstance();
        List<ChannelModel> channelMap = config.getMyChannelModel();


        for(Iterator iter = channelMap.iterator();iter.hasNext();)
        {
             IoHandle io = new IoHandle() {
                public void run(Context context)
                {
                    Dispatch dispatch = new Dispatch();
                    dispatch.run(context);
                }
                @Override
                public void doConnected(Channel session) {

                }
            };

            ChannelModel model = (ChannelModel)iter.next();
//            URL url = URL.valueOf(model.type+"://"+config.getDomain()+".localhost:"+model.port+"?"+ Constant.URL_PAR_MY_NODE_ID
//                    +"="+config.getNodeId()+"&"+Constant.URL_PAR_CHANNEL_NAME+"="+model.name);

            Server ser = (Server) AnoClassCretator.getInstance().createObject(Server.class,model.type);
            ser.startServer(model.getURL(),io);
            servers.add(ser);
        }

    }

    public static void stopServer()
    {
         for(Server server:servers)
         {
             try
             {
                server.stopServer();
             }catch (Exception e)
             {

             }
         }
    }

}
